//
//  WedDetailViewController.m
//  MMLOOK
//
//  Created by dllo on 15/9/28.
//  Copyright © 2015年 武俊娥. All rights reserved.
//

#import "WedDetailViewController.h"
#import "FirstView.h"
#import "LastView.h"
#import "AsynConnect.h"
#import "WedModel.h"
#import "WedDeatilTableViewCell.h"
#import "MBProgressHUD.h"
#import "DataBase.h"
#import "SaveTools.h"
#import "JudgeConnection.h"

#define RealWidth ([UIScreen mainScreen].bounds.size.width - 40 ) / 3

#define Labelwidth  [UIScreen mainScreen].bounds.size.width - 40

@interface WedDetailViewController ()<UITableViewDataSource, UITableViewDelegate>


@property(nonatomic, retain)UITableView *tableView;

@property(nonatomic, retain)NSMutableArray *titleArr;
@property(nonatomic, retain)NSMutableArray *commentArr;
@property(nonatomic, retain)NSMutableArray *recommendArr;

@property(nonatomic, retain)FirstView *myView;
@property(nonatomic, retain)LastView *lastView;

@property(nonatomic, retain)MBProgressHUD *mbProView;

//判断网络请求结束没有
@property(nonatomic, assign)BOOL first;
@property(nonatomic, assign)BOOL second;
@property(nonatomic, assign)BOOL third;

@property(nonatomic, retain)UIAlertController *alert;

@property(nonatomic, retain) UIBarButtonItem *collect;
@property(nonatomic, retain) UIBarButtonItem *share;



@end

@implementation WedDetailViewController


-(void)dealloc
{
    [super dealloc];
}


-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
     
        self.titleArr = [NSMutableArray array];
        self.commentArr = [NSMutableArray array];
        self.recommendArr = [NSMutableArray array];
       
        
    }
    
    return self;
}


-(void)timerAction
{
    [self.alert dismissViewControllerAnimated:YES completion:nil];
    
}



-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}


-(void)getBarButtonImage
{
    self.collect = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@""] style:UIBarButtonItemStylePlain target:self action:@selector(collectButtonAction:)];
    
    self.share = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"share.png"] style:UIBarButtonItemStylePlain target:self action:@selector(shareButtonAction:)];
    
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:self.share,self.collect, nil];
    
    if ([DataBase selectWith:self.model.nameId]) {
        
        self.collect.image = [UIImage imageNamed:@"shi.png"];
        
        
    } else {
        
        self.collect.image = [UIImage imageNamed:@"collect.png"];
        
    }

}


-(void)collectButtonAction:(UIBarButtonItem *)button
{
    
    if ([DataBase insertWithModel:self.model]) {
        
        NSLog(@"%@", self.model);
        
        button.image = [UIImage imageNamed:@"shi.png"];
        
        self.alert = [UIAlertController alertControllerWithTitle:@"收藏成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:self.alert animated:YES completion:nil];
        
        NSTimer *timer = [NSTimer timerWithTimeInterval:3 target:self selector:@selector(timerAction) userInfo:nil repeats:NO];
        
        [timer fire];
        
    } else {
        
        button.image = [UIImage imageNamed:@"collect.png"];
        
        [DataBase deleteWithModel:self.model];
        
        self.alert = [UIAlertController alertControllerWithTitle:@"取消收藏" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:self.alert animated:YES completion:nil];
        
        NSTimer *timer = [NSTimer timerWithTimeInterval:3 target:self selector:@selector(timerAction) userInfo:nil repeats:NO];
        
        [timer fire];

    }
    
    
}

-(void)shareButtonAction:(UIButton *)button
{
    
    
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"商品详情";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tabBarController.tabBar.hidden = YES;
    
    self.tabBarController.tabBar.translucent = YES;
    
    //创建tableView
    [self creatTableView];
    
    //先走本地
    [self readLocal];
    
    //网络请求
    [self connection];
    
}

-(void)readLocal
{
    //headerView
    NSString *urlStr = [NSString stringWithFormat:@"%@/%@.json", @"http://www.hunliji.com/products/", self.model.nameId];
    
    NSData *data = [SaveTools readDataWithName:[urlStr hash] directory:NSLibraryDirectory];
    
    if (data != nil) {
        
        NSDictionary *result = [[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]objectForKey:@"product"] ;
        
        WedModel *model = [[WedModel alloc]initWithDic:result];
        
        [self.titleArr addObject:model];
        
        [model release];
        
        [self.myView sendValue:[self.titleArr firstObject]];
        
    }
    
    
    
    //评论
     NSString *commendUrl = [NSString stringWithFormat:@"%@/%@/replies.json",@"http://www.hunliji.com/products",self.model.nameId];
    
     NSData *commendData = [SaveTools readDataWithName:[commendUrl hash] directory:NSLibraryDirectory];
    
    if (commendData != nil) {
        
        NSArray *result = [[NSJSONSerialization JSONObjectWithData:commendData options:NSJSONReadingMutableContainers error:nil]objectForKey:@"replies"] ;
        
        self.commentArr = [NSMutableArray array];
        
        for (NSDictionary *dic in result) {
            
            WedModel *model = [[WedModel alloc]initWithDic:dic];
            
            [self.commentArr addObject:model];
            
            WedModel *user = [[WedModel alloc]initWithDic:[dic objectForKey:@"user"]];
            
            [model.userArr addObject:user];
            
            [user release];
            
            [model release];
            
            
        }
        
        [self.tableView reloadData];
        
    }
    
    
    //推荐
    NSString *recommendUrl = [NSString stringWithFormat:@"http://www.hunliji.com/productRecommend.json"];
    
     NSData *recommendData = [SaveTools readDataWithName:[recommendUrl hash] directory:NSLibraryDirectory];
    
    if (recommendData != nil) {
        
        NSMutableArray *result = [[NSJSONSerialization JSONObjectWithData:recommendData options:NSJSONReadingMutableContainers error:nil]objectForKey:@"products"];
        
        for (NSDictionary *dic in result) {
            
            WedModel *model = [[WedModel alloc]initWithDic:dic];
            
            [self.recommendArr addObject:model];
            
            [model release];
            
        }
        
        [self.lastView sendMessage:self.recommendArr];

        
    }
    
    
    
    
}


-(void)connection
{
    //添加加载动画
    self.mbProView = [[[MBProgressHUD alloc] initWithView:self.view] autorelease];
    _mbProView.mode = MBProgressHUDModeIndeterminate;// 样式 菊花
    _mbProView.labelText = @"(｢･ω･)｢ 加载中";
    [_mbProView show:YES];
    [self.view addSubview:_mbProView];
    
    if ([JudgeConnection judgeConnection] == 0) {
        
        [_mbProView hide:YES];
        
    }
    
    NSString *urlStr = [NSString stringWithFormat:@"%@/%@.json", @"http://www.hunliji.com/products/", self.model.nameId];
    
    //headerView 的网络请求
    [AsynConnect asynConnectWithUrlstr:urlStr parmater:nil block:^(NSData *data) {
        
        //存入本地
        if (data != nil) {
            
            //写本地缓存
            if ([SaveTools saveDataWithName:[urlStr hash] directory:NSLibraryDirectory data:data]) {
                NSLog(@"存入本地啦");
            }
            
            self.first = YES;
            
            NSDictionary *result = [[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]objectForKey:@"product"] ;
            
            WedModel *model = [[WedModel alloc]initWithDic:result];
            
            [self.titleArr addObject:model];
            
            [model release];
            
            [self.myView sendValue:[self.titleArr firstObject]];
            
            self.model.introduce = model.introduce;
    
            //如果数据都在 动画取消
            if (self.first && self.second && self.third) {
                
                [self.mbProView hide:YES];
                
                [self getBarButtonImage];
                
            }
 
        }
    }];

    
    NSString *commendUrl = [NSString stringWithFormat:@"%@/%@/replies.json",@"http://www.hunliji.com/products",self.model.nameId];
    
    //评论的网络请求
    [AsynConnect asynConnectWithUrlstr:commendUrl parmater:nil block:^(NSData *data) {

        if (data != nil) {
            
            //写本地缓存
            if ([SaveTools saveDataWithName:[commendUrl hash] directory:NSLibraryDirectory data:data]) {
                NSLog(@"存入本地啦");
            }
            
        
        self.second = YES;
        
        NSArray *result = [[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]objectForKey:@"replies"] ;
        
        self.commentArr = [NSMutableArray array];
        
        for (NSDictionary *dic in result) {
            
            WedModel *model = [[WedModel alloc]initWithDic:dic];
            
            [self.commentArr addObject:model];
            
            WedModel *user = [[WedModel alloc]initWithDic:[dic objectForKey:@"user"]];
            
            [model.userArr addObject:user];
            
            [user release];
            
            [model release];
            
            
        }
        
        [self.tableView reloadData];
        
        //如果数据都在 动画取消
        if (self.first && self.second && self.third) {
            
            [self.mbProView hide:YES];
            
            [self getBarButtonImage];
   
        }
    }
        
}];
    
    
    //footerView的请求
    
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"6",@"count", nil];
    
    NSString *recommendUrl = [NSString stringWithFormat:@"http://www.hunliji.com/productRecommend.json"];
    
    [AsynConnect asynConnectWithUrlstr:recommendUrl parmater:dic block:^(NSData *data) {
        
        
        if (data != nil) {
            
            //写本地缓存
            if ([SaveTools saveDataWithName:[recommendUrl hash] directory:NSLibraryDirectory data:data]) {
                NSLog(@"存入本地啦");
            }
            
        
        self.third = YES;
        
        NSMutableArray *result = [[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]objectForKey:@"products"];
        
        for (NSDictionary *dic in result) {
            
            WedModel *model = [[WedModel alloc]initWithDic:dic];
            
            [self.recommendArr addObject:model];
            
            [model release];
            
        }
        
         [self.lastView sendMessage:self.recommendArr];
        
        //如果数据都在 动画取消
        if (self.first && self.second && self.third) {
            
            [self.mbProView hide:YES];
            
            [self getBarButtonImage];
        }
    }
        
}];
    
    
}

-(void)creatTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 + 49) style:UITableViewStylePlain];
    
    self.tableView.delegate =self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
#pragma mark - headerView
    
    self.myView = [[FirstView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 10 + self.view.frame.size.width - 20 + 50 + 30)];
    [_myView release];
    
    self.tableView.tableHeaderView = self.myView;
    
#pragma mark - footerView
    
    self.lastView = [[LastView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40 + RealWidth * 2 + 20)];
    [_lastView release];
    
    
    [self.lastView pushDetailWithSendIdBlock:^(WedModel *model) {
       
        WedDetailViewController *wed = [[WedDetailViewController alloc]init];
        
        [self.navigationController pushViewController:wed animated:YES];
        
        wed.model = model;
        
        [wed release];
        
        
    }];
    
    self.tableView.tableFooterView = self.lastView;
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.commentArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *str = @"= =";
    WedDeatilTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        
        cell = [[[WedDeatilTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str]autorelease];
        
    }
    
    WedModel *model = [self.commentArr objectAtIndex:indexPath.row];
    
    WedModel *model1 = [model.userArr firstObject];
    
    [cell sendValue:model model1:model1];
    
    return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    WedModel *model = [self.commentArr objectAtIndex:indexPath.row];
    
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
    CGRect rect =  [model.content boundingRectWithSize:CGSizeMake(Labelwidth, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    CGFloat height = 50 + rect.size.height;
    
    return height;
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
